package scope

import "gorm.io/gorm"

func WithPage(pageNum, pageSize, maxSize int) IScope {
	if pageNum == 0 && pageSize == 0 {
		pageNum = 1
		pageSize = 10
	}
	return Page{
		PageSize: pageSize,
		MaxSize:  maxSize,
		PageNum:  pageNum,
	}
}

type Page struct {
	PageSize int
	MaxSize  int
	PageNum  int
}

func (p Page) getOffset() int {
	if p.PageNum <= 0 {
		return 0
	}
	return (p.PageNum - 1) * p.PageSize
}

func (p Page) getLimit() int {
	if p.PageSize <= 0 {
		return 10
	} else if p.MaxSize > 0 && p.PageSize > p.MaxSize {
		return p.MaxSize
	}
	return p.PageSize
}

func (p Page) MakeScope() Scope {
	return func(db *gorm.DB) *gorm.DB {
		return db.
			Offset(p.getOffset()).
			Limit(p.getLimit())
	}
}
